package com.atguigu.gulimall.order.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberRespVo;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author : Jungle
 * @Description :  订单页面全部需要登录
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespVo> loginUser = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        ///order/order/status/{orderSn} 匹配路径放行,这些路径不需要登录
        // uri /order/order/status/{orderSn}
        // url是需要带上域名order.gulimall.com/order/status/{orderSn}
        //方法一
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match("/order/order/status/**", uri);
        boolean match1 = antPathMatcher.match("/payed/notify", uri);
        if (match || match1) {
            return true;
        }
        //不用登录就可以访问的路径，白名单路径

        //方法二
        //List<String> paths = Arrays.asList("/payed/notify", "/order/order/status/**");
        ////在所有路径中筛选匹配到路径的项目，返回true
        //List<Boolean> collect = paths.stream().map(path -> {
        //    boolean match = new AntPathMatcher().match(path, uri);
        //    if (match == true) {
        //        //匹配的话直接放行
        //        return true;
        //    }
        //    return false;
        //}).filter(item -> item == true).collect(Collectors.toList());
        ////在白名单中，就放行
        //if (!CollectionUtils.isEmpty(collect)) {
        //    return true;
        //}

        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            loginUser.set(attribute);
            //放行
            return true;
        } else {
            //没登录就去登录
            request.getSession().setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }
    }
}
